package dao.impl;

import dao.AppointmentsDao;
import entity.Appointments;
import entity.RescheduleNotifications;
import entity.myEnum.Status;
import entity.vo.AppointmentsData;
import entity.vo.DoctorsGetAppointments;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DruidUtils;

import java.sql.Connection;
import java.util.List;

public class AppointmentsDaoImpl implements AppointmentsDao {
    @Override
    public int booking(Appointments appointments) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "insert into appointments (user_id, doctors_id, datetime, status) values (?,?,?,?)";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, appointments.getUserId(),
                    appointments.getDoctorsId(), appointments.getDate(), Status.pending.toString());
            DruidUtils.close(null, conn);
            if (update > 0) return update;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return 0;
    }

    @Override
    public List<AppointmentsData> queryByUserId(Integer userId) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT  a.id,d.id as doctorsId ,datetime,status,department,title\n" +
                    "FROM appointments a join doctors d on a.doctors_id = d.id\n" +
                    "where a.user_id=? order by datetime desc";
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            QueryRunner queryRunner = new QueryRunner();
            List<AppointmentsData> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(AppointmentsData.class, basicRowProcessor), userId);
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public List<DoctorsGetAppointments> queryByDoctorsId(Integer doctorsId) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT  a.id ,datetime,status,name,email,phone_number\n" +
                    "            FROM appointments a join users u on a.user_id = u.id\n" +
                    "                where doctors_id=? order by datetime desc";
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            QueryRunner queryRunner = new QueryRunner();
            List<DoctorsGetAppointments> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(DoctorsGetAppointments.class, basicRowProcessor), doctorsId);
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public List<DoctorsGetAppointments> queryOkByDoctorsId(Integer doctorsId) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT  a.id ,datetime,status,name,email,phone_number\n" +
                    "            FROM appointments a join users u on a.user_id = u.id\n" +
                    "                where doctors_id=? and status='confirmed' ";
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            QueryRunner queryRunner = new QueryRunner();
            List<DoctorsGetAppointments> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(DoctorsGetAppointments.class, basicRowProcessor), doctorsId);
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public boolean updateTime(RescheduleNotifications rescheduleNotifications) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "update appointments set  datetime=?where id=?"; //修改预约时间
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s,
                    rescheduleNotifications.getNewDate(), rescheduleNotifications.getAppointmentId());
            //通知表新增数据
            s = "insert into reschedule_notifications(appointment_id, old_date, new_date, status)values (?,?,?,?)";
            int update1 = queryRunner.update(conn, s,
                    rescheduleNotifications.getAppointmentId(), rescheduleNotifications.getOldDate(),
                    rescheduleNotifications.getNewDate(), Status.pending.toString());
            DruidUtils.close(null, conn);
            if ((update + update1) > 1) return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return false;
    }

    @Override
    public int cancelById(Integer id) {
        Connection conn = null;
        try {
            conn = DruidUtils.getConnection();
            //修改预约表中预约的状态
            String s = "update appointments set status='cancelled' where id=?";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, id);
            //通知表，新增通知，状态是"取消";不需要oldDate和newDate
            s = "insert into reschedule_notifications (appointment_id, status)values (?,?)";
            int update1 = queryRunner.update(conn, s, id, Status.cancelled.toString());
            DruidUtils.close(null, conn);
            return (update + update1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return 0;
    }

    @Override
    public int confirmById(Integer id) {
        Connection conn = null;
        try {
            conn = DruidUtils.getConnection();
            //修改预约表中预约的状态
            String s = "update appointments set status='confirmed' where id=?";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, id);
            //通知表，新增通知，状态是"确认";不需要oldDate和newDate
            s = "insert into reschedule_notifications (appointment_id, status)values (?,?)";
            int update1 = queryRunner.update(conn, s, id, Status.confirmed.toString());
            DruidUtils.close(null, conn);
            return (update + update1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DruidUtils.close(null, conn);
        }
        return 0;
    }

    @Override
    public int deleteById(Integer id) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "delete  from appointments where id=?";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, id);
            DruidUtils.close(null, conn);
            if (update > 0) return update;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return 0;
    }
}
